package com.example.test_witns.ui.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.test_witns.R;
import com.example.test_witns.databinding.ActivityLoginBinding;
import com.example.test_witns.pojo.RegisterLoginResponse;
import com.example.test_witns.ui.mine.MineFragment;
import com.example.test_witns.ui.register.RegisterActivity;
import com.example.test_witns.utils.GenerateTestUserSig;
import com.example.test_witns.utils.MyInfosHelper;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMSDKConfig;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

public class LoginActivity extends AppCompatActivity {
    private ActivityLoginBinding binding;
    private String email;
    private String passwordString;
    private String sig;
    private byte[] avatarBytes;
    private String uuid;
    private String nickname;
    private String avatarURL;

    public interface RegisterLoginApiService{
        @POST("RegisterUserEmail")
        Call<RegisterLoginResponse> RegisterUserEmail(@Body String userEmail);

        @GET("checkUserRegistered")
        Call<RegisterLoginResponse> checkUserRegistered(@Query("userEmail") String userEmail);
    }

    public interface OnRegisterLoginInfoReturnListener{
        public void OnRegisterLoginInfoReturn(boolean Registered);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Objects.requireNonNull(getSupportActionBar()).hide();
        Window window = getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.setStatusBarColor(Color.parseColor("#ffffff"));

        View root = binding.getRoot();

        View backToMine = root.findViewById(R.id.chat_backToMine);
        backToMine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        View goto_register = root.findViewById(R.id.goto_register);
        goto_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(intent);
            }
        });

        V2TIMSDKConfig config = new V2TIMSDKConfig();
        config.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_INFO);
        V2TIMManager.getInstance().initSDK(this,1600066337, config);

        View login_confirm = root.findViewById(R.id.login_confirm);
        login_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView login_username = root.findViewById(R.id.login_username);
                email = login_username.getText().toString();
                TextView login_password = root.findViewById(R.id.login_password);
                String password_input = login_password.getText().toString();

                if (!email.isEmpty()){
                    if (!password_input.isEmpty()){
                        checkUserRegistered(email, new OnRegisterLoginInfoReturnListener() {
                            @Override
                            public void OnRegisterLoginInfoReturn(boolean Registered) {
                                if (Registered) tryLogin(password_input, root);
                                else
                                    Toast.makeText(LoginActivity.this, "此账号未注册, 请 注册", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else {
                        Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(LoginActivity.this, "邮箱不能为空", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }

    private void tryLogin(String password_input, View root) {
        sig = GenerateTestUserSig.genTestUserSig(email);
        V2TIMManager.getInstance().login(email, sig, new V2TIMCallback() {
            @Override
            public void onSuccess() {
                MyInfosHelper myInfosHelper = new MyInfosHelper(LoginActivity.this);

                ArrayList<String> userList = new ArrayList<>();
                userList.add(email);
                V2TIMManager.getInstance().getUsersInfo(userList, new V2TIMValueCallback<List<V2TIMUserFullInfo>>() {
                    @Override
                    public void onSuccess(List<V2TIMUserFullInfo> v2TIMUserFullInfos) {
                        for (V2TIMUserFullInfo userinfo:
                                v2TIMUserFullInfos) {
                            byte[] password = userinfo.getCustomInfo().get("password");
                            uuid = new String(userinfo.getCustomInfo().get("uuid"));
                            nickname = userinfo.getNickName();
                            avatarURL = userinfo.getFaceUrl();
                            CircleImageView login_avatar = root.findViewById(R.id.login_avatar);
                            if (LoginActivity.this != null){
                                Glide.with(LoginActivity.this)
                                        .load(avatarURL)
                                        .listener(new RequestListener<Drawable>() {
                                            @Override
                                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                                return false;
                                            }

                                            @Override
                                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                                return false;
                                            }
                                        })
                                        .into(login_avatar);
                                Bitmap bitmap1 = null;
                                if(login_avatar.getDrawable() instanceof BitmapDrawable){
                                    bitmap1 = ((BitmapDrawable)login_avatar.getDrawable()).getBitmap();
                                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                    bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                                    avatarBytes = outputStream.toByteArray();
                                }
                            }
                            passwordString = new String(password);
                            if (password_input.equals(passwordString)){
                                myInfosHelper.addMyInfos(email, nickname, sig, uuid, avatarBytes, null, avatarURL);
                                Intent intent = new Intent(getApplicationContext(), MineFragment.class);
                                startActivity(intent);
                            }else {
                                V2TIMManager.getInstance().logout(new V2TIMCallback() {
                                    @Override
                                    public void onSuccess() {
                                        Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onError(int i, String s) {

                                    }
                                });
                            }
                        }


                    }
                    @Override
                    public void onError(int i, String s) {
                        Toast.makeText(LoginActivity.this, "信息获取失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            @Override
            public void onError(int i, String s) {
                Toast.makeText(LoginActivity.this, "email错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public boolean checkUserRegistered(String userEmail, OnRegisterLoginInfoReturnListener onRegisterLoginInfoReturnListener){
        AtomicBoolean registered = new AtomicBoolean(false);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + "101.35.251.218" + ":8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RegisterLoginApiService registerLoginApiService = retrofit.create(RegisterLoginApiService.class);
        Call<RegisterLoginResponse> call = registerLoginApiService.checkUserRegistered(userEmail);
        call.enqueue(new Callback<RegisterLoginResponse>() {
            @Override
            public void onResponse(Call<RegisterLoginResponse> call, Response<RegisterLoginResponse> response) {
                if (response.body() != null && response.body().getData()) {
                    registered.set(true);
                }
                onRegisterLoginInfoReturnListener.OnRegisterLoginInfoReturn(registered.get());
            }

            @Override
            public void onFailure(Call<RegisterLoginResponse> call, Throwable t) {
                runOnUiThread(() -> {
                    Toast.makeText(LoginActivity.this, "请求注册状态失败, 请检查网络", Toast.LENGTH_SHORT).show();
                });
            }
        });
        return registered.get();
    }
}